package com.sqx.modules.goods.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.utils.PageUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.activityManage.entity.ActivityManage;
import com.sqx.modules.activityManage.service.ActivityManageService;
import com.sqx.modules.app.dao.MsgDao;
import com.sqx.modules.app.dao.UserDao;
import com.sqx.modules.app.entity.Msg;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.entity.UserMoney;
import com.sqx.modules.app.service.UserMoneyService;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.common.entity.CommonInfo;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.datacentre.dao.DataCentreDao;
import com.sqx.modules.datacentre.dao.ShopAdminDao;
import com.sqx.modules.datacentre.entity.SysUserShop;
import com.sqx.modules.goods.dao.GoodsShopDao;
import com.sqx.modules.goods.dao.GoodsShopRelevancyDao;
import com.sqx.modules.goods.entity.Goods;
import com.sqx.modules.goods.entity.GoodsShop;
import com.sqx.modules.goods.entity.GoodsShopRelevancy;
import com.sqx.modules.goods.service.GoodsAttrService;
import com.sqx.modules.goods.service.GoodsShopService;
import com.sqx.modules.goods.vo.GoodsShopVo;
import com.sqx.modules.integral.entity.UserIntegral;
import com.sqx.modules.integral.service.UserIntegralService;
import com.sqx.modules.order.dao.AppOrderDao;
import com.sqx.modules.order.dao.OrderGoodsDao;
import com.sqx.modules.order.entity.OrderGoods;
import com.sqx.modules.order.entity.TbOrder;
import com.sqx.modules.shop.entity.ShopType;
import com.sqx.modules.shop.service.ShopMessageService;
import com.sqx.modules.shop.service.ShopTypeService;
import com.sqx.modules.sys.dao.SysUserDao;
import com.sqx.modules.sys.entity.SysUserEntity;
import com.sqx.modules.sys.service.SysUserRoleService;
import com.sqx.modules.utils.fieYun.FeiYunUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
public class GoodsShopServiceImpl extends ServiceImpl<GoodsShopDao, GoodsShop> implements GoodsShopService {

    @Autowired
    private GoodsShopDao goodsShopDao;
    @Autowired
    private GoodsShopRelevancyDao goodsShopRelevancyDao;
    @Autowired
    private OrderGoodsDao orderGoodsDao;
    @Autowired
    private MsgDao msgDao;
    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private AppOrderDao appOrderDao;
    @Autowired
    private DataCentreDao dataCentreDao;
    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private ShopAdminDao shopAdminDao;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private UserDao userDao;
    @Autowired
    private GoodsAttrService goodsAttrService;
    @Autowired
    private ActivityManageService activityManageService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserMoneyService userMoneyService;
    @Autowired
    private UserIntegralService userIntegralService;
    @Autowired
    private ShopMessageService shopMessageService;
    @Autowired
    private ShopTypeService typeService;


    @Override
    @Transactional
    public Result insertGoodsShop(GoodsShop goodsShop) {
        GoodsShop oldGoodsShop = goodsShopDao.selectOne(new QueryWrapper<GoodsShop>().eq("phone", goodsShop.getPhone()).in("status",0,1));
        if(oldGoodsShop!=null){
            return Result.error("当前手机号已注册！");
        }

        if(StringUtils.isNotEmpty(goodsShop.getSnCode())){
            String s = addPrinter(goodsShop);
            if(!"ok".equals(s)){
                return Result.error(s);
            }
        }
        goodsShop.setShopScore(5.0);
        goodsShop.setShopSales(0);
        goodsShop.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        goodsShop.setStatus(1);
        goodsShop.setErrandMoney(BigDecimal.valueOf(0));
        goodsShop.setDistributionDistance(0.0);
        goodsShop.setPutawayFlag(0);
        goodsShop.setAutoSendOrder(0);
        goodsShop.setAutoAcceptOrder(0);
        goodsShop.setBannedFlag(0);
        baseMapper.insertGoodsShop(goodsShop);
        UserEntity userEntity1 = userService.selectUserById(goodsShop.getUserId());
        SysUserShop sysUserShop = shopAdminDao.selectOne(new QueryWrapper<SysUserShop>().eq("user_id", userEntity1.getAdminUserId()));
        if(sysUserShop!=null){
            sysUserShop.setShopId(goodsShop.getShopId());
            shopAdminDao.updateById(sysUserShop);
            return Result.success();
        }else{
            //添加管理员账号
            SysUserEntity user = new SysUserEntity();
            user.setCreateTime(new Date());
            user.setUsername(goodsShop.getPhone());
            user.setPassword(goodsShop.getPhone());
            user.setMobile(goodsShop.getPhone());
            List<Long> roleIdList = new ArrayList();
            roleIdList.add(12L);
            user.setStatus(1);
            //sha256加密
            String salt = RandomStringUtils.randomAlphanumeric(20);
            user.setPassword(new Sha256Hash(user.getPassword(), salt).toHex());
            user.setSalt(salt);
            user.setUserType(2);
            sysUserDao.insertSysUser(user);
            Long userId = user.getUserId();//返回的主键user_id
            //添加管理员—商铺关联表
            sysUserShop = new SysUserShop();
            sysUserShop.setShopId(goodsShop.getShopId());
            sysUserShop.setUserId(userId);
            shopAdminDao.insert(sysUserShop);
            //保存用户与角色关系
            sysUserRoleService.saveOrUpdate(user.getUserId(), roleIdList);
            //todo 绑定用户和管理用户
            UserEntity userEntity = new UserEntity();
            userEntity.setUserId(goodsShop.getUserId());
            userEntity.setAdminUserId(user.getUserId());
            userEntity.setShopAdminFlag(1);
            userDao.updateById(userEntity);
        }


        return Result.success();
    }


    /**
     * 绑定打印机推送
     *
     * @param goodsShop
     * @return
     */
    public String addPrinter(GoodsShop goodsShop) {
        //目前只有飞鹅pos机可以推送
        if (goodsShop.getFacility()!=null && goodsShop.getFacility().equals(1)) {
            String snlist = goodsShop.getSnCode() + "#" + goodsShop.getValue() + "#" + goodsShop.getShopName();
            String method = FeiYunUtils.addprinter(snlist);
            JSONObject jsonObject = JSON.parseObject(method);
            if (jsonObject != null) {
                if ("0".equals(jsonObject.getString("ret"))) {
                    JSONObject data = jsonObject.getJSONObject("data");
                    JSONArray no = data.getJSONArray("no");
                    if(no.size()>0){
                        String msg = no.getString(0);
                        if(msg.contains("已被添加过")){
                            return "ok";
                        }
                        return no.getString(0);
                    }
                    return "ok";
                }else{
                    return jsonObject.getString("msg");
                }

            }
            return "pos机添加失败！";
        } else {
            return "ok";
        }
    }



    @Override
    public Result updateGoodsShop(GoodsShop goodsShop) {
        GoodsShop goodsShop1 = goodsShopDao.selectById(goodsShop.getShopId());
        if(StringUtils.isNotEmpty(goodsShop.getSnCode())){
            //判断下本次和上次的一样吗 如果一样则不做校验
            if(StringUtils.isNotEmpty(goodsShop1.getSnCode()) && StringUtils.isNotEmpty(goodsShop1.getValue()) ){
                if(!goodsShop1.getSnCode().equals(goodsShop.getSnCode()) || !goodsShop1.getValue().equals(goodsShop.getValue())){
                    String s = addPrinter(goodsShop);
                    if(!"ok".equals(s)){
                        return Result.error(s);
                    }
                    //删除之前的打印机
//                    String snlist = goodsShop1.getSnCode();
//                    FeiYunUtils.deletePrinter(snlist);
                }
            }else{
                String s = addPrinter(goodsShop);
                if(!"ok".equals(s)){
                    return Result.error(s);
                }
            }
        }else{
            //判断之前有没有写过打印机 如果写过 则删除
            if(StringUtils.isNotEmpty(goodsShop1.getSnCode())){
                //删除之前的打印机
//                String snlist = goodsShop1.getSnCode();
//                FeiYunUtils.deletePrinter(snlist);
            }
        }
        if(goodsShop.getBannedFlag()!=null && goodsShop.getBannedFlag().equals(1)){
            goodsShop.setPutawayFlag(1);
//            sendMsgDXB(goodsShop.getPhone(), null, 1);
            userService.sendMsg(goodsShop.getPhone(),"weigui");
        }
        baseMapper.updateById(goodsShop);
        return Result.success();
    }

    /*private Result sendMsgDXB(String phone, String value, Integer type) {
        if(type==2){
            Msg byPhone = msgDao.findByPhone(phone);
            if (byPhone != null) {
                byPhone.setCode(String.valueOf(value));
                byPhone.setPhone(phone);
                msgDao.updateById(byPhone);
            } else {
                Msg msg = new Msg();
                msg.setCode(String.valueOf(value));
                msg.setPhone(phone);
                msgDao.insert(msg);
            }
        }
        CommonInfo three = commonInfoService.findOne(164);
        CommonInfo four = commonInfoService.findOne(165);
        CommonInfo name = commonInfoService.findOne(12);
        value = "【" + name.getValue() + "】 您的店铺因违规操作已被封禁，请联系平台客服！";
        String testUsername = three.getValue(); //在短信宝注册的用户名
        String testPassword = four.getValue(); //在短信宝注册的密码
        StringBuilder httpArg = new StringBuilder();
        httpArg.append("u=").append(testUsername).append("&");
        httpArg.append("p=").append(Md5Utils.md5s(testPassword)).append("&");
        httpArg.append("m=").append(phone).append("&");
        httpArg.append("c=").append(Md5Utils.encodeUrlString(value, "UTF-8"));
        String result = Md5Utils.request("https://api.smsbao.com/sms", httpArg.toString());
        log.error("短信包返回值："+result);
        return Result.success();
    }*/

    @Override
    public Result deleteGoodsShop(Long id) {
        baseMapper.deleteById(id);
        return Result.success();
    }

    @Override
    public Result selectGoodsByShopId(Long shopId, Integer page, Integer limit, String goodsName, Integer classifyId, Integer status) {
        Page<Goods> pages = new Page<>(page, limit);
        PageUtils pageUtils = new PageUtils(goodsShopDao.selectGoodsByShopId(pages, shopId, goodsName, classifyId, status));
        return Result.success().put("data", pageUtils);
    }

    @Override
    public Result selectGoodsByNotShopId(Long shopId, Integer page, Integer limit, String goodsName) {
        Page<Goods> pages = new Page<>(page, limit);
        PageUtils pageUtils = new PageUtils(goodsShopDao.selectGoodsByNotShopId(pages, shopId, goodsName));
        return Result.success().put("data", pageUtils);
    }

    @Override
    public Result addGoodsByShopId(List<GoodsShopRelevancy> goodsShopRelevancyList) {
        String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        goodsShopDao.addGoodsByShopId(goodsShopRelevancyList, date);
        return Result.success();
    }

    @Transactional
    @Override
    public Result deleteGoodsByShopId(Long shopId, Long goodsId) {
        goodsShopDao.deleteGoods(shopId, goodsId);
        goodsShopDao.deleteGoodsByShopId(shopId, goodsId);
        goodsAttrService.deleteGoodsAttr(goodsId);
        return Result.success();
    }

    @Override
    public Result soldOutOrPutaway(Long shopId, Long goodsId, Integer status) {
        goodsShopDao.soldOutOrPutaway(shopId, goodsId,status);
        return Result.success();
    }

    @Override
    public Result updateGoodsByShopId(GoodsShopRelevancy goodsShopRelevancy) {
        goodsShopRelevancyDao.update(goodsShopRelevancy, new QueryWrapper<GoodsShopRelevancy>()
                .eq("shop_id", goodsShopRelevancy.getShopId())
                .eq("goods_id", goodsShopRelevancy.getGoodsId()));
        return Result.success();
    }

    @Override
    public Result selectStoreData(Long shopId, String date, String dateType) {
        HashMap hashMap = new HashMap();
        BigDecimal sumMoney = appOrderDao.selectSumMoney(date, dateType,shopId);
        int countOrder = appOrderDao.selectCountOrder(date, dateType,shopId);
        //到店订单数
        int takeCount = dataCentreDao.selectTakeCount(1, shopId, date, dateType);
        //外卖订单数
        int takeCount2 = dataCentreDao.selectTakeCount(2, shopId, date, dateType);
        //到店订单金额
        BigDecimal takeMoney = dataCentreDao.selectTakeMoney(1, shopId, date, dateType);
        //外卖订单金额
        BigDecimal takeMoney1 = dataCentreDao.selectTakeMoney(2, shopId, date, dateType);
        //退款订单数
        int cancelOrderCount = dataCentreDao.cancelOrderCount(shopId, date, dateType);
        //退款金额
        BigDecimal cancelOrderMoney = dataCentreDao.cancelOrderMoney(shopId, date, dateType);
        hashMap.put("takeCount", takeCount);
        hashMap.put("takeCount2", takeCount2);
        hashMap.put("takeMoney", takeMoney);
        hashMap.put("takeMoney1", takeMoney1);
        hashMap.put("cancelOrderCount", cancelOrderCount);
        hashMap.put("cancelOrderMoney", cancelOrderMoney);
        hashMap.put("count", countOrder);
        hashMap.put("money", sumMoney);
        return Result.success().put("hashMap", hashMap);
    }

    @Override
    public Result selectStoreMessage(Long shopId, String startTime, String endTime, Integer page, Integer limit, String orderNumber) {
        Page<TbOrder> pages = new Page<>(page, limit);
        IPage<TbOrder> tbOrderIPage = goodsShopDao.selectStoreMessage(pages, shopId, startTime, endTime, orderNumber);
        List<TbOrder> records = tbOrderIPage.getRecords();
        for(int i = 0;i<records.size();i++){
            List<OrderGoods> orderGoodsList = orderGoodsDao.selectList(new QueryWrapper<OrderGoods>()
                    .eq("order_id", records.get(i).getOrderId()));
            tbOrderIPage.getRecords().get(i).setOrderGoodsList(orderGoodsList);
        }
        PageUtils pageUtils = new PageUtils(tbOrderIPage);
        return Result.success().put("data", pageUtils);
    }

    @Override
    public Result quickGoodsShop(GoodsShopVo goodsShopVo) {
        GoodsShop goodsShop = goodsShopDao.selectOne(new QueryWrapper<GoodsShop>().eq("phone", goodsShopVo.getPhone()).in("status",0,1));
        if(goodsShop!=null){
            return Result.error("当前手机号已注册！");
        }
        String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        UserEntity userInfo = userService.queryByPhone(goodsShopVo.getPhone());
        if(userInfo!=null){
            goodsShopVo.setUserId(userInfo.getUserId());
        }else{
            userInfo=new UserEntity();
            //填充前端传递的相关参数
            userInfo.setPhone(goodsShopVo.getPhone());
            //添加默认头像
            CommonInfo one = commonInfoService.findOne(232);
            userInfo.setAvatar(one.getValue());
            userInfo.setNickName(goodsShopVo.getPhone().replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2"));
            userInfo.setPlatform(goodsShopVo.getPlatform());
            userInfo.setPassword(DigestUtils.sha256Hex(goodsShopVo.getPhone()));
            userInfo.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            userInfo.setSysPhone(goodsShopVo.getSysPhone());
            userInfo.setStatus(1);
            //用户类型
            userInfo.setUserType(goodsShopVo.getUserType());
            if (goodsShopVo.getUserType() == 1) {
                userInfo.setWxOpenId(goodsShopVo.getOpenId());
            } else if (goodsShopVo.getUserType() == 2) {
                userInfo.setRiderWxOpenId(goodsShopVo.getOpenId());
            }
            userInfo.setUpdateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            //新用户注册，加新用户标识
            userInfo.setNewUserFlag(1);
            userInfo.setNewUserFlagWm(1);
            //新注册用户钱包余额和保证金为0
            userInfo.setBalance(BigDecimal.valueOf(0));
            userInfo.setCashDeposit(BigDecimal.valueOf(0));
            userInfo.setIsVip(0);
            userDao.insertUser(userInfo);
            //注册新账号的时候，创建钱包
            UserMoney userMoney = new UserMoney();
            userMoney.setUserId(userInfo.getUserId());
            userMoney.setMoney(new BigDecimal(0));
            userMoneyService.save(userMoney);
            //注册新账号得时候，创建积分仓库
            UserIntegral userIntegral = new UserIntegral();
            userIntegral.setUserId(userInfo.getUserId());
            userIntegral.setIntegralNum(0);
            userIntegralService.save(userIntegral);
            goodsShopVo.setUserId(userInfo.getUserId());
        }
        Msg msg1 = msgDao.findByPhoneAndCode(goodsShopVo.getPhone(), goodsShopVo.getMsg());
        //校验短信验证码
        if (msg1 == null) {
            return Result.error("验证码不正确");
        }
        msgDao.deleteById(msg1.getId());
        goodsShopVo.setCreateTime(format);
        goodsShopVo.setStatus(0);
        goodsShopVo.setBannedFlag(0);
        goodsShopVo.setCashDeposit(0.00);
        goodsShopVo.setMinimumDelivery(BigDecimal.ZERO);
        goodsShopVo.setExemptMinMoney(BigDecimal.ZERO);
        goodsShopVo.setExemptErrandFlag(1);
        goodsShopVo.setErrandMoney(BigDecimal.ZERO);
        goodsShopVo.setDistributionDistance(3000.00);
        GoodsShop shop = new GoodsShop();
        BeanUtils.copyProperties(goodsShopVo, shop);
        baseMapper.insert(shop);
        CommonInfo name = commonInfoService.findOne(12);
        Msg byPhone = msgDao.findByPhone(goodsShopVo.getPhone());
        if (byPhone != null) {
            byPhone.setCode(String.valueOf(goodsShopVo.getMsg()));
            byPhone.setPhone(goodsShopVo.getPhone());
            msgDao.updateById(byPhone);
        } else {
            Msg msg = new Msg();
            msg.setCode(String.valueOf(goodsShopVo.getMsg()));
            msg.setPhone(goodsShopVo.getPhone());
            msgDao.insert(msg);
        }
        return userService.sendMsg(goodsShopVo.getPhone(),"jieguo");
    }

    /*private Result goodsShopMsgDXB(String phone, String value) {
        CommonInfo three = commonInfoService.findOne(164);
        CommonInfo four = commonInfoService.findOne(165);
        String testUsername = three.getValue(); //在短信宝注册的用户名
        String testPassword = four.getValue(); //在短信宝注册的密码
        StringBuilder httpArg = new StringBuilder();
        httpArg.append("u=").append(testUsername).append("&");
        httpArg.append("p=").append(Md5Utils.md5s(testPassword)).append("&");
        httpArg.append("m=").append(phone).append("&");
        httpArg.append("c=").append(Md5Utils.encodeUrlString(value, "UTF-8"));
        String result = Md5Utils.request("https://api.smsbao.com/sms", httpArg.toString());
        log.error("短信包返回值："+result);
        return Result.success();
    }*/

    @Override
    public Result selectGoodsShop(String phone,String msg){
        Msg msg1 = msgDao.findByPhoneAndCode(phone, msg);
        //校验短信验证码
        if (msg1 == null) {
            return Result.error("验证码不正确");
        }
        msgDao.deleteById(msg1.getId());
        GoodsShop goodsShop = goodsShopDao.selectGoodShopByPhone(phone);
        return Result.success().put("data",goodsShop);
    }

    @Override
    public Integer cancelActivityShop(Long activityId, Long shopId) {
        return goodsShopDao.cancelActivityShop(activityId,shopId);


    }

    @Override
    public ActivityManage getShopActivity(Long shopId) {
        GoodsShop goodsShop = goodsShopDao.selectById(shopId);
        ShopType shopType = typeService.getById(goodsShop.getShopTypeId());
        if(shopType!=null){
            goodsShop.setShopTypeName(shopType.getShopTypeName());
        }
       return activityManageService.getById(goodsShop.getActivityId());


    }


}
